package com.bawei.module_live.ui.fragment

import android.app.Dialog
import android.os.Bundle
import android.os.CountDownTimer
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bawei.module_live.R
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.bawei.module_live.databinding.FragmentLiveBinding
import com.bawei.module_live.databinding.FragmentOrderHotAllBinding
import com.bawei.module_live.databinding.FragmentOrderHotDaihuoBinding
import com.bawei.module_live.ui.LiveIntent
import com.bawei.module_live.ui.LiveState
import com.bawei.module_live.ui.LiveViewModel
import com.bawei.module_live.ui.adapter.OrderHotAdapter
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import com.bawei.module_live.data.OrderHotData
import android.app.AlertDialog

class OrderHotDaihuoFragment : Fragment() {

    private var _binding: FragmentOrderHotDaihuoBinding? = null
    private val binding get() = _binding!!
    private lateinit var liveViewModel: LiveViewModel
    private lateinit var adapter: OrderHotAdapter

    private var countDownTimer: CountDownTimer? = null
    private val oneHourMillis = 60 * 60 * 1000L
    private lateinit var tvCountdown: TextView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentOrderHotDaihuoBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        liveViewModel = ViewModelProvider(requireActivity())[LiveViewModel::class.java]
        adapter = OrderHotAdapter(mutableListOf(), useTop3Special = false, isDaihuoRanking = true)
        binding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
        binding.recyclerView.adapter = adapter

        tvCountdown = binding.timerBar.findViewById(R.id.tvCountdown)
        startCountdown()

        // 1. 读取榜单类型参数
        val type = arguments?.getInt("type") ?: 0
        lifecycleScope.launch {
            liveViewModel.intents.send(LiveIntent.FetchOrderHotListIntent(type.toString()))
        }

        lifecycleScope.launch {
            liveViewModel.liveState.collectLatest { state ->
                when (state) {
                    is LiveState.OrderHotListSuccess -> {
                        adapter.updateData(state.orderHotList)
                    }
                    is LiveState.Error -> {
                        Toast.makeText(requireContext(), state.errorMsg, Toast.LENGTH_SHORT).show()
                    }
                    else -> {}
                }
            }
        }

        binding.btnRule.setOnClickListener { showRuleDialog() }

        // 3. 点击事件
        adapter.onItemClick = { item ->
            AlertDialog.Builder(requireContext())
                .setMessage("是否跳转到${item.room_name}的直播间？")
                .setPositiveButton("确定") { dialog, _ ->
                    (requireActivity() as? OnRankingItemClickListener)?.onRankingItemClicked(item)
                    dialog.dismiss()
                }
                .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                .show()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
        countDownTimer?.cancel()
    }

    private fun startCountdown() {
        countDownTimer?.cancel()
        countDownTimer = object : CountDownTimer(oneHourMillis, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                val min = millisUntilFinished / 1000 / 60
                val sec = (millisUntilFinished / 1000 % 60)
                tvCountdown.text = "倒计时 %02d:%02d".format(min, sec)
            }
            override fun onFinish() {
                startCountdown() // 重新开始
            }
        }.start()
    }
    private fun showRuleDialog() {
        val dialog = Dialog(requireContext(), R.style.CustomDialog) // 可自定义样式
        dialog.setContentView(R.layout.dialog_rule)
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)

        // 设置规则内容
        val tvRuleContent = dialog.findViewById<TextView>(R.id.bangdan)
        tvRuleContent.text = "带货榜单规则"


        // 返回按钮
        dialog.findViewById<View>(R.id.btnBack).setOnClickListener {
            dialog.dismiss()
        }

        dialog.show()
    }
}